#include "core.h"
#include "JsonEncoding.h"


//----------------------------------------------------------------------------------------------------------------------------
BOOL CJsonEncoding::load( const CHAR * begin, const CHAR * end,  Json::Value &root )
{
	Json::Reader json_reader;
	return json_reader.parse( begin, end, root );
}

BOOL CJsonEncoding::loadStr( std::string& strJson, Json::Value& root )
{
	return load( strJson.c_str(), strJson.c_str()+strJson.length() , root );
}

//----------------------------------------------------------------------------------------------------------------------------
BOOL CJsonEncoding::load( const std::string &file,  Json::Value &root )
{
	fpos_t pos = 0;
	FILE* pfile = NULL;
	fopen_s( &pfile, file.c_str(), "rb" );
	if ( pfile != 0 )
	{
		fseek( pfile, 0, SEEK_END );
		fgetpos( pfile, &pos );
		fclose( pfile );
	}

	char* file_buffer = new char[ pos+ 6 ];
	memset(file_buffer, 0, pos+6);

	fopen_s( &pfile, file.c_str(), "rb" );
	fread( file_buffer, 1, pos+6, pfile );
	fclose( pfile );

	Json::Reader json_reader;
	BOOL bRet = json_reader.parse( file_buffer, file_buffer + pos, root );

	delete[] file_buffer;
	return bRet;
}

//----------------------------------------------------------------------------------------------------------------------------
BOOL CJsonEncoding::save( const std::string &file,  Json::Value &root )
{
	Json::FastWriter json_writer;
	std::string json_str = json_writer.write( root );
	FILE *pfile = NULL;
	fopen_s( &pfile, file.c_str(), "wb" );
	if ( pfile == NULL )
	{
		return FALSE;
	}

	fwrite( json_str.c_str(), 1, json_str.length(), pfile );
	fclose( pfile );

	return TRUE;
}
